﻿using AutoMapper;
using Mapster;
using SqlSugar;
using Zhp.Common.WebApp;
using Zhp.Entity.Sys;
using Zhp.IService.Sys;
using Zhp.Model.Sys;
using Zhp.Service.Base;
using Zhp.SqlSugar.Repository;

namespace Zhp.Service.Sys
{
    public class SysRoleMenuService : BaseService<SysRoleMenu>, ISysRoleMenuService
    {
        IBaseRepository<SysMenu> _sysMenuRep;
        public SysRoleMenuService(ICurrentUser currentUser, IBaseRepository<SysRoleMenu> rep, IBaseRepository<SysMenu> sysMenuRep)
        {
            _currentUser = currentUser;
            _rep = rep;
            _sysMenuRep = sysMenuRep;
        }
        
        public async Task<(List<RoleMenuModel>, List<string>)> GetRoleMenu(long roleId)
        {
            var menuList = await _sysMenuRep.AsQueryable().ToTreeAsync(x => x.Children, x => x.ParentId, null);

            var roleMenuList = await _rep.GetListAsync(x => x.RoleId == roleId);

            var rList = menuList.Adapt<List<RoleMenuModel>>();

            var menuIdList = roleMenuList.Select(x => x.MenuId).ToList();

            var menuIdLeafList = await _sysMenuRep.AsQueryable().Where(x => menuIdList.Contains(x.Id)).Select(x => x.Id.ToString()).ToListAsync();

            return (rList, menuIdLeafList);
        }

        public async Task<bool> Create(RoleMenuCreate create)
        {
            using (var uow = _rep.Context.CreateContext(_rep.Context.Ado.IsNoTran()))
            {
                await _rep.DeleteAsync(x => x.RoleId == create.RoleId);

                var roleMenuList = new List<SysRoleMenu>();
                foreach (var item in create.MenuIdList)
                {
                    roleMenuList.Add(new SysRoleMenu
                    {
                        RoleId = create.RoleId,
                        MenuId = item,
                    });
                }
                await _rep.InsertRangeAsync(roleMenuList);

                return uow.Commit();
            }
        }
    }
}
